package com.FOD.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.FOD.clases.DateCalendar;
import com.FOD.clases.DateSchedule;
import com.FOD.clases.OptionsAdmin;
import com.FOD.clases.R;
import com.FOD.entities.Cita;
import com.FOD.entities.EmpleadoHorario;
import com.FOD.entities.PacienteUsuario;
import com.FOD.entities.User;
import com.FOD.util.EncryptMessages;
import com.FOD.util.SessionDBHandler;
import com.FOD.util.UtilVar;
import com.FOD.web.DatesFunctions;
import com.FOD.web.UsersFunctions;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ScheduleAdapter extends BaseAdapter {

	private final int SATURDAY_SCHEDULE = 6;
	private final int NORMAL_SCHEDULE = 10;
	private final int OPENING = 8;

	private final Context context;
	private Calendar today;
	private String[] hours;
	private String currentHour;
	private ArrayList<String> dates;
	private ArrayList<Cita> datesList;
	private ArrayList<User> userList;
	private HashMap<String, Cita> dateMap;
	private HashMap<String, User> userMap;
	private int currentStatus;
	private int currentId;

	ProgressDialog pDialog;
	private int userType;

	public ScheduleAdapter(Context c, Calendar t) {
		context = c;
		today = t;
		SessionDBHandler db = new SessionDBHandler(context);
		userType = db.getUserType();
		db.close();
		dates = new ArrayList<String>();
		refreshHours();
	}

	public void setDates(ArrayList<String> dates, ArrayList<Cita> datesObj,
			int userType) {
		this.dates = dates;
		this.datesList = datesObj;
		this.userType = userType;
		dateMap = new HashMap<String, Cita>();
		for (int i = 0; i < datesObj.size(); i++) {
			dateMap.put(datesObj.get(i).getHorario(), datesObj.get(i));
		}
	}

	public void setDates(ArrayList<String> dates, ArrayList<Cita> datesObj,
			ArrayList<User> userList, int userType) {
		this.userType = userType;
		this.dates = dates;
		this.datesList = datesObj;
		dateMap = new HashMap<String, Cita>();
		userMap = new HashMap<String, User>();
		for (int i = 0; i < datesObj.size(); i++) {
			dateMap.put(datesObj.get(i).getHorario(), datesObj.get(i));
			userMap.put(datesObj.get(i).getHorario(), userList.get(i));
		}
	}

	@Override
	public int getCount() {
		return hours.length;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		View view = null;
		switch (userType) {
		case 1:
			view = getDoctorView(position, convertView, parent);
			break;

		case 2:
			view = getTherapistView(position, convertView, parent);
			break;

		case 3:
			view = getPatientView(position, convertView, parent);
			break;
		}
		return view;
	}

	public View getDoctorView(final int position, View convertView,
			ViewGroup parent) {
		TextView hour;
		View v = convertView;

		LayoutInflater vi = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		v = vi.inflate(R.layout.schedule_item, null);

		hour = (TextView) v.findViewById(R.id.hour);
		hour.setText(hours[position]);
		final Cita cita = (Cita) dateMap.get(hours[position]);
		if (!dates.contains(hours[position]) || 
				cita.getEstado() == UtilVar.REFUSE_DATE || 
				cita.getEstado() == UtilVar.CANCEL_DATE) {
			ImageView dateImage = (ImageView) v.findViewById(R.id.dateImage);

			dateImage.setImageDrawable(context.getResources().getDrawable(
					R.drawable.ic_no_date));
			dateImage.setClickable(false);
			dateImage.setFocusable(false);

		} else {
			ImageView dateImage = (ImageView) v.findViewById(R.id.dateImage);
			dateImage.setClickable(true);
			dateImage.setFocusable(true);
			
			if (cita.getEstado() == UtilVar.ACCEPT_DATE) {
				/** Cuando la cita ya esta aceptada y lista para ser atendida **/
				dateImage.setImageDrawable(context.getResources().getDrawable(
						R.drawable.dateicon));
				dateImage.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						AlertDialog.Builder dialogo1 = new AlertDialog.Builder(
								context);
						dialogo1.setTitle("Modificar Cita");
						dialogo1.setMessage("Desea modificar el estatus de esta cita?");
						dialogo1.setCancelable(false);
						dialogo1.setPositiveButton("Cancelar Cita",
								new DialogInterface.OnClickListener() {
									public void onClick(
											DialogInterface dialogo1, int id) {
										currentStatus = UtilVar.CANCEL_DATE;
										currentId = cita.getId();
										new UpdateDate().execute();
									}
								});
						dialogo1.setNegativeButton("No modificar",
								new DialogInterface.OnClickListener() {
									public void onClick(
											DialogInterface dialogo1, int id) {
									}
								});
						dialogo1.show();
					}
				});
			} else if (cita.getEstado() == UtilVar.PENDING_DATE) {
				/** Cuando la cita aun esta pendiente de ser aceptada **/
				dateImage.setImageDrawable(context.getResources().getDrawable(
						R.drawable.ic_take_date));
				dateImage.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						AlertDialog.Builder dialogo1 = new AlertDialog.Builder(
								context);
						dialogo1.setTitle("Cita Solicitada");
						dialogo1.setMessage("Desea aceptar esta cita?");
						dialogo1.setCancelable(false);
						dialogo1.setPositiveButton("Aceptar Cita",
								new DialogInterface.OnClickListener() {
									public void onClick(
											DialogInterface dialogo1, int id) {
										currentStatus = UtilVar.ACCEPT_DATE;
										currentId = cita.getId();
										new UpdateDate().execute();
									}
								});
						dialogo1.setNegativeButton("Rechazar Cita",
								new DialogInterface.OnClickListener() {
									public void onClick(
											DialogInterface dialogo1, int id) {
										currentStatus = UtilVar.REFUSE_DATE;
										currentId = cita.getId();
										new UpdateDate().execute();
									}
								});
						dialogo1.show();
					}
				});
			}

			if (cita.getEstado() != UtilVar.REFUSE_DATE && cita.getEstado() != UtilVar.CANCEL_DATE) {
				TextView name = (TextView) v.findViewById(R.id.costumerName);
				name.setText(((User) userMap.get(hours[position])).getName());
				TextView reason = (TextView) v.findViewById(R.id.costumerCase);
				reason.setText(cita.getEstado() == UtilVar.ACCEPT_DATE ? "Cita Confirmada": "Pendiente por Confirmar");
			}

		}
		return v;
	}

	public View getPatientView(final int position, View convertView,
			ViewGroup parent) {
		TextView hour;
		View v = convertView;

		LayoutInflater vi = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		v = vi.inflate(R.layout.schedule_item, null);

		hour = (TextView) v.findViewById(R.id.hour);
		hour.setText(hours[position]);
		if (!dates.contains(hours[position])) {
			ImageView dateImage = (ImageView) v.findViewById(R.id.dateImage);

			dateImage.setImageDrawable(context.getResources().getDrawable(
					R.drawable.adddate));

			dateImage.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					currentHour = hours[position];
					new MakeDate().execute();
				}
			});
		} else {
			v.setClickable(false);
			v.setFocusable(false);
			ImageView dateImage = (ImageView) v.findViewById(R.id.dateImage);

			dateImage.setImageDrawable(context.getResources().getDrawable(
					R.drawable.dateicon));

		}
		return v;
	}

	public View getTherapistView(final int position, View convertView,
			ViewGroup parent) {
		TextView hour;
		View v = convertView;

		LayoutInflater vi = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		v = vi.inflate(R.layout.schedule_item, null);

		hour = (TextView) v.findViewById(R.id.hour);
		hour.setText(hours[position]);
		if (!dates.contains(hours[position])) {
			ImageView dateImage = (ImageView) v.findViewById(R.id.dateImage);

			dateImage.setImageDrawable(context.getResources().getDrawable(
					R.drawable.adddate));

			dateImage.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					currentHour = hours[position];
					new MakeDate().execute();
				}
			});
		} else {
			v.setClickable(false);
			v.setFocusable(false);
			ImageView dateImage = (ImageView) v.findViewById(R.id.dateImage);

			dateImage.setImageDrawable(context.getResources().getDrawable(
					R.drawable.dateicon));
			if (userType == 1) {
				TextView name = (TextView) v.findViewById(R.id.costumerName);
				name.setText("Rafael Jacobo Galindo");
				TextView reason = (TextView) v.findViewById(R.id.costumerCase);
				reason.setText("Esguince en tobillo");
			}

		}
		return v;
	}

	public void refreshHours() {

		int day = today.get(Calendar.DAY_OF_WEEK);

		if (day == 7) {
			hours = new String[SATURDAY_SCHEDULE];
		} else {
			hours = new String[NORMAL_SCHEDULE];
		}

		for (int i = 0; i < hours.length; i++) {
			String schedule = String.valueOf(OPENING + i);
			if (schedule.length() == 1) {
				hours[i] = "0" + schedule + ":00";
			} else {
				hours[i] = schedule + ":00";
			}
		}
	}

	private void makeDatePatient(String hour) {

		// Creamos Objeto User Function para la conexion
		DatesFunctions datesFunctions = new DatesFunctions();
		SessionDBHandler db = new SessionDBHandler(context);
		// Creamos un JSON y le asignamos el json que regresa la conexion al
		// servidor
		JSONObject json = datesFunctions.makeDate(today.getTime(), hour,
				new Date(), db.getPatientUserDetails().getId());

		// Verificamos la respuesta del servidor en el JSON
		try {
			// SI el tag no viene null
			if (json.getString(UtilVar.KEY_SUCCES) != null) {
				String res = json.getString(UtilVar.KEY_SUCCES);

				if (Integer.parseInt(res) == 1) {
					// JSONObject json_user = json.getJSONObject("date");
					Log.w("DATE", "Cita creada");
				} else {
					Log.w("DATE", "Cita no creada cheka error");
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.w("DATE", "Esta exepcion");
		}
	}

	private void updateDate(int dateId, int status) {

		// Creamos Objeto User Function para la conexion
		DatesFunctions datesFunctions = new DatesFunctions();
		SessionDBHandler db = new SessionDBHandler(context);
		// Creamos un JSON y le asignamos el json que regresa la conexion al
		// servidor
		JSONObject json = datesFunctions.updateDate(dateId, status);

		// Verificamos la respuesta del servidor en el JSON
		try {
			// SI el tag no viene null
			if (json.getString(UtilVar.KEY_SUCCES) != null) {
				String res = json.getString(UtilVar.KEY_SUCCES);

				if (Integer.parseInt(res) == 1) {

					Log.w("DATE", "Cita actualizada");
				} else {
					Log.w("DATE", "Cita no actualizada cheka error");
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.w("DATE", "Esta exepcion");
		}
	}

	private class MakeDate extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(context);
			pDialog.setMessage("Creando cita..");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			makeDatePatient(currentHour);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (pDialog.isShowing()) {
				pDialog.dismiss();
			}
			Intent intent = new Intent(context, DateCalendar.class);
			context.startActivity(intent);
			// populateSpinner();
		}
	}

	private class UpdateDate extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(context);
			pDialog.setMessage("Modificando estado..");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			updateDate(currentId, currentStatus);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (pDialog.isShowing()) {
				pDialog.dismiss();
			}
		}
	}

}
